package com.spzx.product.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.product.api.model.ProductSku;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.*;
import com.spzx.product.vo.CategoryVo;
import com.spzx.product.vo.IndexDataVo;
import com.spzx.product.vo.ItemVo;
import com.spzx.product.vo.ProductSkuVo;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: atguigu
 * @create: 2025-04-30 15:02
 */
@RestController
@RequestMapping("/channel")
public class ChannelController extends BaseController {

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IProductSkuService productSkuService;


    @Autowired
    private ISkuStockService skuStockService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IProductDetailsService productDetailsService;

    /**
     * 首页数据
     *
     * @return
     */
    @Operation(summary = "首页数据")
    @GetMapping("/index")
    public AjaxResult indexData() {
        //1.创建首页VO对象
        IndexDataVo vo = new IndexDataVo();
        //2.封装一级分类列表
        List<CategoryVo> categoryVoList = categoryService.getLevelOneCategory();
        vo.setCategoryList(categoryVoList);

        //3.封装畅销TOP20商品列表
        List<ProductSkuVo> productSkuList = productSkuService.selectTopSale();
        vo.setProductSkuList(productSkuList);

        //4.响应VO
        return AjaxResult.success(vo);
    }


    /**
     * 查询所有分类
     *
     * @return
     */
    @Operation(summary = "查询所有分类")
    @GetMapping("/category")
    public AjaxResult categoryList() {
        List<CategoryVo> categoryVoList = categoryService.tree();
        return AjaxResult.success(categoryVoList);
    }


    /**
     * 分页条件查询商品列表
     *
     * @param pageNum
     * @param pageSize
     * @param skuQuery
     * @return
     */
    @Operation(summary = "分页条件查询商品列表")
    @GetMapping("/skuList/{pageNum}/{pageSize}")
    public TableDataInfo skuList(
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize,
            SkuQuery skuQuery
    ) {
        //1.开始分页
        PageHelper.startPage(pageNum, pageSize);
        //2.根据条件查询商品SKU列表
        List<ProductSkuVo> list = productSkuService.selectSkuList(skuQuery);
        return getDataTable(list);
    }

    @Autowired
    private IBrandService brandService;

    @Operation(summary = "获取全部品牌")
    @GetMapping("/brand")
    public AjaxResult selectBrandAll() {
        return success(brandService.list());
    }


    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 封装商品SKU详情页所需数据
     *
     * @param skuId 商品SKUID
     * @return
     */
    @Operation(summary = "封装商品SKU详情页所需数据")
    @GetMapping("/item/{skuId}")
    public AjaxResult item(@PathVariable("skuId") Long skuId) {
        //TODO: 解决缓存穿透问题：判断用户访问商品ID是否存在
        Boolean flag = redisTemplate.opsForValue().getBit("product:sku:data", skuId);
        if (!flag) {
            throw new ServiceException("访问商品不存在");
        }

        //1.创建ItemVo对象
        ItemVo itemVo = new ItemVo();
        //2.为ItemVo中七项属性逐一赋值
        //2.1 根据商品SKUID查询商品SKU信息  异步需要返回结果：商品SKU信息返回提供给 轮播图任务、详情图片任务、规格参数任务 使用
        CompletableFuture<Long> productIdCompletableFuture = CompletableFuture.supplyAsync(() -> {
            ProductSku skuInfo = productSkuService.getSkuInfo(skuId);
            itemVo.setProductSku(skuInfo);
            return skuInfo.getProductId();
        }, threadPoolExecutor);
        //2.2 查询商品SKU价格
        itemVo.setSkuPrice(productSkuService.getSkuPrice(skuId));
        //2.3 查询商品SKU库存
        itemVo.setSkuStock(skuStockService.getSkuStock(skuId));
        //2.4 查询商品轮播图列表  依赖商品ID异步任务，不需要有返回结果
        CompletableFuture<Void> imageCompletableFuture = productIdCompletableFuture.thenAcceptAsync(productId -> {
            Product product = productService.getById(productId);
            if (product != null && StringUtils.isNoneBlank(product.getSliderUrls())) {
                String sliderUrls = product.getSliderUrls();
                itemVo.setSliderUrlList(sliderUrls.split(","));
            }
            //2.5 查询商品详情图片列表
            ProductDetails productDetails = productDetailsService.getOne(
                    new LambdaQueryWrapper<ProductDetails>()
                            .eq(ProductDetails::getProductId, productId)
            );
            if (productDetails != null && StringUtils.isNoneBlank(productDetails.getImageUrls())) {
                itemVo.setDetailsImageUrlList(productDetails.getImageUrls().split(","));
            }
            //2.6 查询商品规格信息，展示规格信息用于用户选择
            String specValue = product.getSpecValue();
            if (StringUtils.isNoneBlank(specValue)) {
                JSONArray jsonArray = JSON.parseArray(specValue);
                itemVo.setSpecValueList(jsonArray);
            }
        }, threadPoolExecutor);
        //2.7 封装商品规格参数跟SKUID映射关系Map
        CompletableFuture<Void> skuSpecMapCompletableFuture = productIdCompletableFuture.thenAcceptAsync(productId -> {
            itemVo.setSkuSpecValueMap(productSkuService.getSkuSpecValue(productId));
        }, threadPoolExecutor);

        //3.阻塞线程，等待所有任务完成
        CompletableFuture
                .allOf(
                        productIdCompletableFuture,
                        imageCompletableFuture,
                        skuSpecMapCompletableFuture)
                .join();
        //3.响应ItemVo
        return success(itemVo);
    }


}
